package com.loongtech.bi.action.biflow;

import com.loongtech.bi.action.Base2BiSearchAction;
import com.loongtech.bi.entity.flow.ConsumeAndAddcashRankModel;
import com.loongtech.bi.manager.flow.HadoopQueryManager;
import com.loongtech.bi.manager.system.BiPlatformManager;
import com.loongtech.bi.manager.system.GameParamConfigManager;
import com.loongtech.bi.support.CommonGameParam;
import com.loongtech.core.util.NumberUtil;
import com.loongtech.core.util.Time;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.Map.Entry;

/**
 * 
 * ClassName: CurrencyConsumeRankingFlowNewAction
 * 
 * @Description: 消耗排行流水
 * @author liuchen
 * @date 2017-5-17 下午7:01:53
 */
@Controller
@Scope("prototype")
@RequestMapping("/flow/currencyConsumeRankingFlow")
public class CurrencyConsumeRankingFlowNewAction extends Base2BiSearchAction {
	private static final long serialVersionUID = 1L;
	@Autowired
	HadoopQueryManager hadoopQueryManager;

	/**
	 * 
	 * @Description: TODO 获取参数
	 * @param @param request
	 * @param @param response
	 * @param @param callback
	 * @return void
	 * @throws
	 * @author liuchen
	 */
	@RequestMapping(value = "initParam.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void initParam(HttpServletRequest request, HttpServletResponse response, String callback) {
		try {
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "0");
			result.put("serverItmes", serverItmes);
			result.put("typeItmes", GameParamConfigManager.getItems(CommonGameParam.CURRENCY_TYPE));
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	protected Date day = new Date(Time.getBeginningOfDay(Time.currentTime() - 1 * Time.DAY));
	private Map<String, String> allRechargeTypeRevise = GameParamConfigManager
			.getItemsRevise(CommonGameParam.RECHARGE_CURRENCY_TYPE); // 充值相关类型

	@RequestMapping(value = "search.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void search(HttpServletRequest request, HttpServletResponse response, @RequestParam String params,
			String callback) {
		Map<String, Object> re = new HashMap<String, Object>();
		Map<String, ConsumeAndAddcashRankModel> tmpMap = new HashMap<String, ConsumeAndAddcashRankModel>();
		List<Object[]> consumeResult = new ArrayList<>();
		List<Object[]> addcashResult = new ArrayList<>();
		List<ConsumeAndAddcashRankModel> result = new ArrayList<>();
		try {
			Map<String, Object> m = jsonToMap(params);
			String serverid = (String) m.get("serverid");
			Integer typeItem = Integer.valueOf((String) m.get("type"));

			if (HadoopQueryManager.VISIT_QUEUE.offer("CurrencyConsumeRankingFlowNewAction")) {
				System.out.println("VISIT_QUEUE offer CurrencyConsumeRankingFlowNewAction ok!");
				// 消耗查询
				StringBuffer sql2 = new StringBuffer();

				// 如果是全部充值类型
				if (typeItem == 99999) {
					sql2.append("select 99999,userid,serverid,sum(wholeconsume) as totalconsume from totalrolecurrencyconsume where dt = '"
							+ Time.getDateStr(day) + "' ");

					StringBuilder currencytype = new StringBuilder();
					currencytype.append("(");

					int sum = 0;

					// 货币类型传递
					for (Map.Entry<String, String> entry : allRechargeTypeRevise.entrySet()) {
						String type = entry.getKey();

						if (sum == 0) {
							currencytype.append(type);
						} else {
							currencytype.append("," + type);
						}

						sum++;
					}

					currencytype.append(")");

					sql2.append("and currencytype in " + currencytype.toString());

					if (!"0".equals(serverid)) {
						sql2.append(" and serverid = ");
						sql2.append(serverid);
					}

					sql2.append(" group by userid,serverid order by totalconsume asc limit 1000 ");
				} else {
					sql2.append("select currencytype,userid,serverid,sum(wholeconsume) as totalconsume from totalrolecurrencyconsume where dt = '"
							+ Time.getDateStr(day) + "' ");

					sql2.append(" and currencytype = ");
					sql2.append(typeItem);

					if (!"0".equals(serverid)) {
						sql2.append(" and serverid = ");
						sql2.append(serverid);
					}

					sql2.append(" group by currencytype,userid,serverid order by totalconsume asc limit 10000 ");
				}

				Entry<List<String>, List<Object[]>> ret2 = hadoopQueryManager.executeSQL(sql2.toString());
				if (null == ret2 || null == ret2.getKey() || ret2.getKey().isEmpty() || null == ret2.getValue()) {
					re.put("res", "1");
					re.put("msg", "查询结果为空!");
					printToJson(response, re, callback);
					return;
				}

				consumeResult = ret2.getValue();

				// 消费排行
				long consumeIndex = 0;

				for (Object[] obj : consumeResult) {
					ConsumeAndAddcashRankModel model = new ConsumeAndAddcashRankModel();
					model.setConsumeIndex(++consumeIndex);
					model.setComnsumeCurrencytype(Integer.parseInt(String.valueOf(obj[0])));
					model.setConsumeUserid(String.valueOf(obj[1]));
					model.setConsumeServerid(String.valueOf(obj[2]));
					model.setWholeconsume(Long.parseLong(String.valueOf(obj[3])));

					// 加入
					result.add(model);
				}

				// 充值查询
				StringBuffer sql1 = new StringBuffer();
				sql1.append("select userid,sum(wholecashadd)/100 as totalcash from totalroleaddcash where userid != '' and dt = '"
						+ Time.getDateStr(day) + "'");

				// 增加服务器条件
				if (!"0".equals(serverid)) {
					sql1.append(" and serverid = ");
					sql1.append(serverid);
				}

				sql1.append(" group by userid order by totalcash desc limit 1000 ");

				Entry<List<String>, List<Object[]>> ret1 = hadoopQueryManager.executeSQL(sql1.toString());
				if (null == ret1 || null == ret1.getKey() || ret1.getKey().isEmpty() || null == ret1.getValue()) {
                    re.put("res", new ArrayList<Object[]>());
                    re.put("data", "");
                    printToJson(response, re, callback);
					return;
				}

				addcashResult = ret1.getValue();
				// 货币消耗排行
				long addcashIndex = 0;
				// 货币消耗
				for (Object[] obj : addcashResult) {
					ConsumeAndAddcashRankModel model = new ConsumeAndAddcashRankModel();
					model.setAddcashIndex(++addcashIndex);
					model.setAddcashUserid(String.valueOf(obj[0]));
					model.setWholecashadd((long) Double.parseDouble(String.valueOf(obj[1])));

					//
					tmpMap.put(String.valueOf(obj[0]), model);
				}

				// 迭代
				for (ConsumeAndAddcashRankModel model : result) {
					// 货币消耗的user id
					String consumeUserid = model.getConsumeUserid();
					//
					ConsumeAndAddcashRankModel tmpModel = tmpMap.get(consumeUserid);

					if (tmpModel != null) {
						model.setAddcashIndex(tmpModel.getAddcashIndex());
						model.setAddcashUserid(tmpModel.getAddcashUserid());
						model.setWholecashadd(tmpModel.getWholecashadd());
					}
				}

				List<Object[]> lo = new ArrayList<Object[]>();
				for (ConsumeAndAddcashRankModel model : result) {
					Object[] o = { model.getConsumeIndex(),
							BiPlatformManager.getServerNameById(model.getConsumeServerid()), model.getAddcashUserid(),
							getMoneyType(model.getComnsumeCurrencytype()) + "(" + model.getComnsumeCurrencytype() + ")", model.getConsumeUserid(),
							model.getWholeconsume(), model.getAddcashIndex(), model.getWholecashadd() };
					lo.add(o);
				}
				re.put("res", "0");
				re.put("data", lo);
				printToJson(response, re, callback);
			} else {
				System.out.println("VISIT_QUEUE offer CurrencyConsumeRankingFlowNewAction failed!");

				re.put("res", "1");
				re.put("msg", "当前系统正被访问，为保证服务器稳定，请稍后再试!");
				printToJson(response, re, callback);
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			re.put("res", "1");
			re.put("msg", e.getMessage());
			printToJson(response, re, callback);
		}
	}

	private Map<String, String> typeItmesRevise = GameParamConfigManager.getItemsRevise(CommonGameParam.CURRENCY_TYPE); // MoneyTypeManager.reasonItmesRevise;
																														// //
																														// 货币类型反转

	// 元宝类型
	public String getMoneyType(Object currencyType) {
		// 全部充值类型
		if (NumberUtil.parseInt(currencyType) == 99999) {
			return "全部充值相关类型";
		}

		String key = currencyType == null ? "" : Math.abs(Integer.parseInt(currencyType.toString())) + "";
		return (typeItmesRevise.get(key) == null) ? key : typeItmesRevise.get(key);
	}

	@Override
	public void search() {
		// TODO Auto-generated method stub

	}

	@Override
	protected String csvContent() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected String csvFileName() {
		// TODO Auto-generated method stub
		return null;
	}
}
